﻿using System;
using Quartz;
using Quartz.Impl;

namespace Common.util
{
    public class QuartzUtils
    {
        private static QuartzUtils _quartzUtils;

        private static readonly object Locker = new object();
        private IScheduler _scheduler;


        private QuartzUtils()
        {
            Init();
        }

        public static QuartzUtils GetInstance()
        {
            if (_quartzUtils == null)
            {
                lock (Locker)
                {
                    if (_quartzUtils == null)
                    {
                        _quartzUtils = new QuartzUtils();
                    }
                }
            }
            return _quartzUtils;
        }

        private void Init()
        {
            StdSchedulerFactory factory = new StdSchedulerFactory();
            _scheduler = factory.GetScheduler();

            _scheduler.Start();
        }

        public void Destory()
        {
            _scheduler.Shutdown();
        }
        /// <summary>
        /// cron任务
        /// </summary>
        public static void Cron<T>(String cron) where T : IJob
        {
            IJobDetail job = JobBuilder.Create<T>()
                .Build();

            ITrigger trigger = TriggerBuilder.Create()
                .WithCronSchedule(cron)
                .Build();
                  
            GetInstance()._scheduler.ScheduleJob(job, trigger);
        }
    }
}